var prefix = jsctx + "/tenant/user";

var user = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        },10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageTenantUser",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20],
                    pageNumber: 1,
                    sidePagination: "server",
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            // userType:'0',
                            loginName: $('#loginName').val().trim(),
                            mobile: $('#mobile').val().trim(),
                            // realName: $('#realName').val().trim(),
                            // tenantRoleId: $('#tenantRoleId').val(),
                            // status: $('#status').val()
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '',width:'50',align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'tenantUserId', title: 'id'},
                        {field: 'loginName', title: '用户名称'},
                        {field: 'mobile', title: '手机号'},
                        {field: 'roleName', title: '角色'},
                        {field: 'createdBy', title: '创建人'},
                        {field: 'mobile', title: '联系方式'},
                        {field: 'createdTime', title: '创建时间'},
                        {field: 'lastLoginTime', title: '最近登陆时间'},
                        {field :'status' , title :'状态', formatter: status_switch},
                        {
                            title: '操作',
                            field: 'roleId',
                            width:'400',align: 'center',
                            formatter: function (value, row, index) {
                                var e = '';
                                if (row.roleType!='2'&&row.roleType!='3'){
                                    e = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="编辑" onclick="user.edit(\''
                                        + row.tenantUserId + '\')"><i class="fa fa-edit">编辑</i></a> ';
                                }
                                var r = '<a class="btn btn-success btn-sm" href="#" title="重置密码" onclick="user.resetPwd(\''
                                    + row.tenantUserId + '\',' + '\'' + row.loginName + '\')"><i class="fa fa-key">重置密码</i></a> ';
                                var d = '<a class="btn btn-warning btn-sm ' + has_delete + '" href="#" title="删除" onclick="user.remove(\''
                                    + row.tenantUserId + '\',' + '\'' + row.loginName + '\')"><i class="fa fa-remove">删除</i></a> ';
                                if (row.userType == '0'){
                                     return '';
                                }
                                return e + r + d;
                            }
                        }
                    ],onLoadSuccess: function(){

                    },onPageChange: function() {

                    }
                });
    }

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                loginName: $('#loginName').val().trim(),
                mobile: $('#mobile').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function status_switch(value, row, index) {
        if (row.userType == '0') {
            return;
        }
        if (value == '0') {
            return  '<input class="tgl tgl-skewed" onclick="user.onSwitchChange(' + row.tenantUserId +',1 )" id="cb'+row.tenantUserId+'" type="checkbox"><label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.tenantUserId+'"></label>'
        } else {
            return '<input class="tgl tgl-skeweds"  onclick="user.onSwitchChange(' + row.tenantUserId +',0 )" id="cb'+row.tenantUserId+'" type="checkbox"> <label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.tenantUserId+'"></label>'
        }
    }






    function onSwitchChange (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateUserStatus",
            data: {
                status: state,
                id:isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
                let errorMsg = xhr.responseText;
                openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
            }
        });
    }
    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function addTenantUser() {
        location.href = prefix + "/addTenantUser";
    }

    function remove(id, name) {
        layer.confirm('确定要删除选中的记录？' + name, {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/remove",
                type: "post",
                data: {
                    'id': id
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function edit(tenantUserId) {
        location.href = prefix + "/editTenantUser/" + tenantUserId;
    }

    function resetPwd(id, name) {
        layer.open({
            type: 1,
            title: '重置密码',
            closeBtn: false,
            shade: 0.4,
            shift: 7,
            shadeClose: true,
            content: `<div style='width:350px;padding:10px;text-align: left'>
                        <div >
                        <span style="font-size: 14px;display: inline-block;width: 90px;text-align: right">新密码:</span>
                        <input type="password" id="newPassword" autocomplete="new-password"  style="width: 150px;height: 30px;margin-left: 10px;text-align: center" >
                        </div>
                        <div style="margin-top: 10px">
                        <span style="font-size: 14px;display: inline-block;width: 90px;text-align: right">确认新密码:</span>
                        <input type="password" id="newPassword2" autocomplete="new-password" style="width: 150px;height: 30px;margin-left: 10px;text-align: center">
                        </div>
                       </div>`,
            btn: ['确定', '取消'],
            yes: function (index) {//layer.msg('yes');    //点击确定回调
                if ($("#newPassword").val() != $("#newPassword2").val()) {
                    layer.msg("两次密码不一致");
                    return;
                }
                layer.close(index);
                $.ajax({
                    url: prefix + "/resetPwd",
                    type: "post",
                    data: {
                        'id': id,
                        'newPassword':$("#newPassword").val()
                    },
                    success: function (data) {
                        layer.close(index);
                        if (data.status == 200) {
                            layer.msg("成功重置密码");
                            reLoad();
                        } else {
                            layer.msg(data.message);
                        }
                    }
                });
            },
        });

    }

    function getTreeData() {
        $.ajax({
            type: "GET",
            url: jsctx+ "/tenant/sysDept/tree",
            success: function (tree) {
                loadTree(tree);
            }
        });
    }

    function loadTree(tree) {
        $('#jstree').jstree({
            'core': {
                'data': tree
            },
            "plugins": ["search"]
        });
        $('#jstree').jstree().open_all();
    }

    $('#jstree').on("changed.jstree", function (e, data) {
        if (data.selected == -1) {
            var opt = {
                query: {
                    deptId: '',
                }
            }
            $('#exampleTable').bootstrapTable('refresh', opt);
        } else {
            var opt = {
                query: {
                    deptId: data.selected[0],
                }
            }
            $('#exampleTable').bootstrapTable('refresh', opt);
        }

    });

    function goBack() {
        location.href = prefix + "/index";
    }

    function openOrg() {
        layer.open({
            type: 2,
            title: "选择组织",
            area: ['300px', '450px'],
            content:jsctx+ "/tenant/org/openTreeView"
        })
    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        addTenantUser: addTenantUser,
        edit: edit,
        resetPwd: resetPwd,
        remove: remove,
        onSwitchChange:onSwitchChange,
        exportList: exportList,
        openOrg: openOrg
    };
})();

var addUser = (function () {
    function init() {
        validateRule();
    };


    function save() {
        // $("#roleIds").val(getCheckedRoles());
        $.ajax({
            cache: true,
            type: "POST",
            url:prefix + "/save",
            data: $('#frmUser').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    user.goBack();
                } else {
                    parent.layer.alert(data.message)
                }

            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmUser").validate({
            rules: {
                loginName: {
                    required: true,
                    minlength: 5
                },
                realName: "required",
                password: {
                    required: true,
                    minlength: 6
                },
                mobile: {
                    required: true,
                    minlength: 11,
                    maxlength: 11
                },
                tenantRoleId:{
                    required: true,
                }
            },
            messages: {
                loginName: {
                    required: icon + "请输入登录帐号",
                    minlength: icon + "名称必须5个字符以上"
                },
                realName: icon + "请输入用户名",
                mobile: {
                    required: icon + "请输入手机号码",
                    minlength: icon + "手机号码少于11位",
                    maxlength: icon + "手机号码超过11位"
                },
                password: {
                    required: icon + "请输入密码",
                    minlength: icon + "密码必须6个字符以上"
                },
                tenantRoleId: icon + "请选择角色",
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();

var editUser = (function () {
    function init() {
        validateRule();
    };

    function update() {
        var formData = new FormData($("#frmUser")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: jsctx+"/tenant/user/save",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    user.goBack();
                } else {
                    parent.layer.msg(data.message);
                }

            }
        });
    }


    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmUser").validate({
            rules: {
                loginName: {
                    required: true,
                    minlength: 2
                },
                realName: "required",
                password: {
                    required: true,
                    minlength: 6
                },
                mobile: {
                    required: true,
                    minlength: 11,
                    maxlength: 11
                },
                tenantRoleId:{
                    required: true,
                }
            },
            messages: {
                loginName: {
                    required: icon + "请输入登录帐号",
                    minlength: icon + "名称必须2个字符以上"
                },
                realName: icon + "请输入用户名",
                mobile: {
                    required: icon + "请输入手机号码",
                    minlength: icon + "手机号码少于11位",
                    maxlength: icon + "手机号码超过11位"
                },
                password: {
                    required: icon + "请输入密码",
                    minlength: icon + "密码必须6个字符以上"
                },
                tenantRoleId: icon + "请选择角色",
            },
            submitHandler: function () {
                update();
            }
        });
    }

    return {
        init: init
    };
})();

